package cn.lh.spider.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;

import cn.lh.spider.dao.IFilter;
import cn.lh.spider.dao.ITask;
import cn.lh.spider.entity.Filter;
import cn.lh.spider.entity.Task;
import tool.StaticTools;


@RequestMapping("/task")
@Controller
public class TaskController {
	@Resource
	private ITask taskS;
	@Resource
	private IFilter filterS;
	
	@RequestMapping("/insert")
	public void insertTask(HttpServletRequest req,HttpServletResponse resp){
		String json1 =null;
		try{
			Task task = new Task();
			List<Filter> filterList = new ArrayList<Filter>();
			List<String> titlefn = new ArrayList<String>();
			List<String> contentfn = new ArrayList<String>();
			List<String> datefn = new ArrayList<String>();
			task.setId(StaticTools.getUUID());
			task.setArticletype(req.getParameter("articletype"));
			task.setWebsitename(req.getParameter("websitename"));
			task.setEntryurl(req.getParameter("entryurl"));
			task.setTaskstate("停止");
			task.setListsrule(req.getParameter("listsrule"));
			task.setListsrex(req.getParameter("listsrex"));
			task.setWritingrule(req.getParameter("writingrule"));
			task.setWritingrex(req.getParameter("writingrex"));
			task.setUrlrex(req.getParameter("urlrex"));
			task.setPagerule(req.getParameter("pagerule"));
			task.setPagerex(req.getParameter("pagerex"));
			task.setPagesuffix(req.getParameter("pagesuffix"));
			task.setTitlerule(req.getParameter("titlerule"));
			task.setContentrule(req.getParameter("contentrule"));
			task.setReleasedaterule(req.getParameter("releasedaterule"));
			Enumeration<String> paramName = req.getParameterNames();
			while(paramName.hasMoreElements()){
				String param = paramName.nextElement();
				 if(param.startsWith("titlefilter")){
					titlefn.add(param);
				}else if(param.startsWith("contentfilter")){
					contentfn.add(param);
				}else if(param.startsWith("releasedatefilter")){
					datefn.add(param);
				}
			}
		
			if(!titlefn.isEmpty()){
				String tuuid = StaticTools.getUUID();
				task.setTitlefilter(tuuid);
				for(int m=0;m<(titlefn.size()/2);m++){
					Filter filter = new Filter();
					filter.setId(StaticTools.getUUID());
					filter.setReferenceid(tuuid);
					filter.setTorder(req.getParameter("titlefilter["+m+"][order]"));
					filter.setFilter(req.getParameter("titlefilter["+m+"][filter]"));
					filterList.add(filter);
				}
			}
			if(!contentfn.isEmpty()){
				String tuuid = StaticTools.getUUID();
				task.setContentfilter(tuuid);
				for(int m=0;m<(contentfn.size()/2);m++){
					Filter filter = new Filter();
					filter.setId(StaticTools.getUUID());
					filter.setReferenceid(tuuid);
					filter.setTorder(req.getParameter("contentfilter["+m+"][order]"));
					filter.setFilter(req.getParameter("contentfilter["+m+"][filter]"));
					filterList.add(filter);
				}
			}
			if(!datefn.isEmpty()){
				String tuuid = StaticTools.getUUID();
				task.setReleasedatefilter(tuuid);
				for(int m=0;m<(datefn.size()/2);m++){
					Filter filter = new Filter();
					filter.setId(StaticTools.getUUID());
					filter.setReferenceid(tuuid);
					filter.setTorder(req.getParameter("releasedatefilter["+m+"][order]"));
					filter.setFilter(req.getParameter("releasedatefilter["+m+"][filter]"));
					filterList.add(filter);
				}
			}
			taskS.insertTask(task);
			if(!filterList.isEmpty()){
				Iterator<Filter> iter = filterList.iterator();
				while(iter.hasNext()){
					filterS.insertFilter(iter.next());
				}
			}
			json1 = "{\"success\":true}";
		}catch(Exception e){
			json1 = "{\"success\":false}";
		}finally {
			resp.setCharacterEncoding("utf-8");
			resp.setContentType("application/json;charset=utf-8");
			try {
				resp.getWriter().print(json1);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}		
	
	@RequestMapping("/data")
	public void getTaskData(int page,int rows,HttpServletResponse resp){
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json;charset=utf-8");
		List<Task> json = taskS.getData((page-1)*rows, rows);
		String json1 = JSON.toJSONString(json);
		int count = taskS.countTask();
		json1 = "{\"total\":"+count+",\"rows\":"+json1+"}";
		try {
			resp.getWriter().print(json1);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/deltask")
	public void delTask(HttpServletRequest req,HttpServletResponse resp){
		int num = req.getParameterMap().size();
		for(int i =0;i<(num/11);i++){
			String id = req.getParameter("deltask["+i+"][id]");
			Task task= taskS.findById(id);
			String titlefilter = task.getTitlefilter();
			String contentfilter = task.getContentfilter();
			String datefilter = task.getReleasedatefilter();
			
			filterS.delFilter(titlefilter);
			filterS.delFilter(contentfilter);
			filterS.delFilter(datefilter);
			taskS.delTask(id);
		}
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/json;charset=utf-8");
		String json1 = "{\"success\":true}";
		try {
			resp.getWriter().print(json1);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	@RequestMapping("/edit")
	public String edit(String id,HttpServletRequest req){
		Task task = taskS.findById(id);
		
		String titlefilter = task.getTitlefilter();
		String contentfilter = task.getContentfilter();
		String datefilter = task.getReleasedatefilter();
		 List<Filter> titlefilterlist = filterS.findByReferid(titlefilter);
		 List<Filter> contentfilterlist = filterS.findByReferid(contentfilter);
		 List<Filter> datefilterlist = filterS.findByReferid(datefilter);
		 String titletab ="var titletab=" + JSON.toJSONString(titlefilterlist);
		 String contenttab ="var contenttab=" + JSON.toJSONString(contentfilterlist);
		 String datetab ="var datetab=" + JSON.toJSONString(datefilterlist);
		req.setAttribute("task", task);
	
		req.setAttribute("titletab", titletab);
		req.setAttribute("contenttab", contenttab);
		req.setAttribute("datetab", datetab);
		return "/task/task_edit";
	}
	
	@RequestMapping("/edittask")
	public void editTask(HttpServletRequest req,String id,HttpServletResponse resp){
		String json1 =null;
		try{
			Task task1= taskS.findById(id);
		
			String titlefilter = task1.getTitlefilter();
			String contentfilter = task1.getContentfilter();
			String datefilter = task1.getReleasedatefilter();
		
			filterS.delFilter(titlefilter);
			filterS.delFilter(contentfilter);
			filterS.delFilter(datefilter);
			taskS.delTask(id);
			//根据taskid，拿到该任务，根据各个过滤项拿到参考id
			//先删掉该任务和过滤项，重新根据任务内容生成各种id,并插入该记录
			Task task = new Task();
			List<Filter> filterList = new ArrayList<Filter>();
			List<String> titlefn = new ArrayList<String>();
			List<String> contentfn = new ArrayList<String>();
			List<String> datefn = new ArrayList<String>();
			task.setId(StaticTools.getUUID());
			task.setArticletype(req.getParameter("articletype"));
			task.setWebsitename(req.getParameter("websitename"));
			task.setEntryurl(req.getParameter("entryurl"));
			task.setTaskstate("停止");
			task.setListsrule(req.getParameter("listsrule"));
			task.setListsrex(req.getParameter("listsrex"));
			task.setWritingrule(req.getParameter("writingrule"));
			task.setWritingrex(req.getParameter("writingrex"));
			task.setUrlrex(req.getParameter("urlrex"));
			task.setPagerule(req.getParameter("pagerule"));
			task.setPagerex(req.getParameter("pagerex"));
			task.setPagesuffix(req.getParameter("pagesuffix"));
			task.setTitlerule(req.getParameter("titlerule"));
			task.setContentrule(req.getParameter("contentrule"));
			task.setReleasedaterule(req.getParameter("releasedaterule"));
			Enumeration<String> paramName = req.getParameterNames();
			while(paramName.hasMoreElements()){
				String param = paramName.nextElement();
				 if(param.startsWith("titlefilter")){
					titlefn.add(param);
				}else if(param.startsWith("contentfilter")){
					contentfn.add(param);
				}else if(param.startsWith("releasedatefilter")){
					datefn.add(param);
				}
			}
			
			if(!titlefn.isEmpty()){
				String tuuid = StaticTools.getUUID();
				task.setTitlefilter(tuuid);
				for(int m=0;m<(titlefn.size()/2);m++){
					Filter filter = new Filter();
					filter.setId(StaticTools.getUUID());
					filter.setReferenceid(tuuid);
					filter.setTorder(req.getParameter("titlefilter["+m+"][torder]"));
					filter.setFilter(req.getParameter("titlefilter["+m+"][filter]"));
					filterList.add(filter);
				}
			}
			if(!contentfn.isEmpty()){
				String tuuid = StaticTools.getUUID();
				task.setContentfilter(tuuid);
				for(int m=0;m<(contentfn.size()/2);m++){
					Filter filter = new Filter();
					filter.setId(StaticTools.getUUID());
					filter.setReferenceid(tuuid);
					filter.setTorder(req.getParameter("contentfilter["+m+"][torder]"));
					filter.setFilter(req.getParameter("contentfilter["+m+"][filter]"));
					filterList.add(filter);
				}
			}
			if(!datefn.isEmpty()){
				String tuuid = StaticTools.getUUID();
				task.setReleasedatefilter(tuuid);
				for(int m=0;m<(datefn.size()/2);m++){
					Filter filter = new Filter();
					filter.setId(StaticTools.getUUID());
					filter.setReferenceid(tuuid);
					filter.setTorder(req.getParameter("releasedatefilter["+m+"][torder]"));
					filter.setFilter(req.getParameter("releasedatefilter["+m+"][filter]"));
					filterList.add(filter);
				}
			}
			//有
			
			taskS.insertTask(task);
			if(!filterList.isEmpty()){
				Iterator<Filter> iter = filterList.iterator();
				while(iter.hasNext()){
					filterS.insertFilter(iter.next());
				}
			}
			json1 = "{\"success\":true}";
		}catch(Exception e){
			json1 = "{\"success\":false}";
		}finally {
			resp.setCharacterEncoding("utf-8");
			resp.setContentType("application/json;charset=utf-8");
			try {
				resp.getWriter().print(json1);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

